﻿#pragma execution_character_set("utf-8")

#include "MainWindow.h"

#include <QAction>
#include <QBoxLayout>
#include <QCheckBox>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QRegExp>
#include <QString>
#include <QStringList>
#include <QTableWidgetItem>

#include "WidgetPanel.h"

// 自定义排序项
class CustomTableWidgetItem : public QTableWidgetItem
{
public:
    explicit CustomTableWidgetItem(const QString &text)
        : QTableWidgetItem(text)
    {
    }

    SortMethod m_sortMethd = SortMethod::S;

    // 重载 < 操作符，实现自定义排序
    bool operator<(const QTableWidgetItem &other) const override
    {
        const CustomTableWidgetItem *otherItem =
            dynamic_cast<const CustomTableWidgetItem *>(&other);
        if (!otherItem) return QTableWidgetItem::operator<(other);

        QString thisText = text();
        QString otherText = otherItem->text();

        if (m_sortMethd == SortMethod::S)
        {
            return thisText < otherText;
        }
        else if (m_sortMethd == SortMethod::N)
        {
            return thisText.toInt() < otherText.toInt();
        }
        else
        {
            // 特殊处理某一列：比如“数字+字母”格式，如 "10A", "2B"
            // 提取前缀数字部分和后缀字母部分
            QRegExp re1("(\\d+)([a-zA-Z]*)");
            int thisPos = re1.indexIn(thisText);

            QRegExp re2("(\\d+)([a-zA-Z]*)");
            int otherPos = re2.indexIn(otherText);

            if (thisPos != -1 && otherPos != -1)
            {
                int thisNum = re1.cap(1).toInt();
                int otherNum = re2.cap(1).toInt();
                QString thisAlpha = re1.cap(2);
                QString otherAlpha = re2.cap(2);

                if (thisNum != otherNum)
                    return thisNum > otherNum;  // 先按数字排序
                return thisAlpha.toLower() <
                       otherAlpha.toLower();  // 再按字母排序
            }

            // 如果不能解析，则回退到默认字符串排序
            return thisText.toLower() < otherText.toLower();
        }
    }
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    m_vecColumn = {
        {"PID", SortMethod::S, 70},    {"PName", SortMethod::S, 250},
        {"CName", SortMethod::S, 250}, {"CType", SortMethod::S, 50},
        {"Rating", SortMethod::S, 50}, {"Date", SortMethod::S, 180},
        {"Solved", SortMethod::S, 50}, {"OtherUser", SortMethod::S, 200},
        {"Tags", SortMethod::S, 100}};

    setWindowTitle("OI Tool for DouDou");

    m_panel = new WidgetPanel();
    m_panel->m_mainWindw = this;

    m_panel->setFixedWidth(550);
    m_panel->setupUI();
    m_panel->configToUI();

    setupUI();

    this->showMaximized();

    m_panel->slotSearchCF();
}

void MainWindow::onHeaderClicked(int logicalIndex)
{
    // 定义允许排序的列索引（例如：第0列和第2列允许排序）
    static Qt::SortOrder order = Qt::AscendingOrder;
    order = (order == Qt::AscendingOrder) ? Qt::DescendingOrder
                                          : Qt::AscendingOrder;

    // 临时启用排序
    tableWidget->setSortingEnabled(true);

    tableWidget->sortByColumn(logicalIndex, order);

    // 排序完成后，立即关闭排序功能，防止其他列自动排序
    tableWidget->setSortingEnabled(false);
}

void MainWindow::onCellClicked(int row, int column)
{
    if (column == 0)
    {
        QString url = tableWidget->item(row, 0)->data(Qt::UserRole).toString();
        QDesktopServices::openUrl(QUrl(url));
    }
}

std::vector<QTableWidgetItem *> MainWindow::appendOneRow(
    int nRow, const QStringList &lstText, bool bCF, const QColor &clrText,
    const QColor &clrBK)
{
    std::vector<QTableWidgetItem *> vecItem;
    for (int i = 0; i < lstText.size(); ++i)
    {
        CustomTableWidgetItem *item = new CustomTableWidgetItem(lstText[i]);
        item->m_sortMethd = m_vecColumn[i].sort;
        item->setForeground(QBrush(clrText));
        item->setBackground(QBrush(clrBK));
        tableWidget->setItem(nRow, i, item);

        vecItem.push_back(item);
    }

    return vecItem;
}

void MainWindow::setupUI()
{
    tableWidget = new QTableWidget(this);
    QFont font("SimSun", 20);
    // tableWidget->setFont(font);
    // tableWidget->verticalHeader()->setDefaultSectionSize(60);
    QWidget *wgt = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setMargin(0);
    layout->addWidget(tableWidget);
    layout->addWidget(m_panel);
    wgt->setLayout(layout);

    setCentralWidget(wgt);

    tableWidget->setColumnCount(m_vecColumn.size());

    QStringList lst;
    for (const auto &[_label, _, _1] : m_vecColumn)
    {
        lst.push_back(_label);
    }
    tableWidget->setHorizontalHeaderLabels(lst);

    tableWidget->verticalHeader()->setVisible(false);
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableWidget->setAlternatingRowColors(true);
    tableWidget->setSortingEnabled(false);
    // 连接水平表头的 sectionClicked 信号
    connect(tableWidget->horizontalHeader(), &QHeaderView::sectionClicked, this,
            &MainWindow::onHeaderClicked);

    for (int i = 0; i < m_vecColumn.size(); ++i)
    {
        tableWidget->setColumnWidth(i, m_vecColumn[i].nWidth);
        tableWidget->horizontalHeader()->setSectionResizeMode(
            0, QHeaderView::Interactive);
    }
    tableWidget->horizontalHeader()->setStretchLastSection(true);

    connect(tableWidget, &QTableWidget::cellClicked, this,
            &MainWindow::onCellClicked);
}

void MainWindow::setTableMode(TableMode mode)
{
    if (TableMode::CF == mode)
    {
        m_vecColumn = {
            {"PID", SortMethod::NS, 180},   {"PName", SortMethod::S, 550},
            {"CName", SortMethod::S, 30},   {"CType", SortMethod::S, 180},
            {"Rating", SortMethod::N, 180}, {"Date", SortMethod::S, 520},
            {"Solved", SortMethod::N, 160}, {"OtherUser", SortMethod::S, 200},
            {"Tags", SortMethod::S, 100}};
    }
    else if (TableMode::ATCoder == mode)
    {
        m_vecColumn = {
            {"ID", SortMethod::S, 250},     {"PName", SortMethod::S, 550},
            {"CName", SortMethod::S, 30},   {"CType", SortMethod::S, 180},
            {"Rating", SortMethod::N, 100}, {"Date", SortMethod::S, 520},
            {"Solved", SortMethod::N, 160}, {"OtherUser", SortMethod::S, 200},
            {"Tags", SortMethod::S, 100}};
    }
    else
    {
        m_vecColumn = {
            {"ID", SortMethod::S, 250},     {"PName", SortMethod::S, 550},
            {"CName", SortMethod::S, 30},   {"CType", SortMethod::S, 180},
            {"Rating", SortMethod::N, 100}, {"Date", SortMethod::S, 520},
            {"Solved", SortMethod::N, 160}, {"Week", SortMethod::S, 200},
            {"Tags", SortMethod::S, 100}};
    }

    for (int i = 0; i < m_vecColumn.size(); ++i)
    {
        tableWidget->model()->setHeaderData(i, Qt::Horizontal,
                                           m_vecColumn[i].strLabel);
        tableWidget->setColumnWidth(i, m_vecColumn[i].nWidth);
    }
}
